package com.ltmonitor.web.controller.command;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.entity.TerminalCommand;
import com.ltmonitor.service.JT808Constants;
import com.ltmonitor.web.util.JsonMessage;

/**
 * 终端控制
 * 
 * @author DELL
 * 
 */

@Controller
@RequestMapping("/terminalControl")
public class TerminalControlAction extends TerminalCommandAction {
	// 控制类型
	@RequestMapping("/view.action")
	public String view(long vehicleId, Model m) {
		m.addAttribute("vehicleId", vehicleId);
		return "/command/terminalControl";
	}
	
	@RequestMapping("/viewWirelessUpdate.action")
	public String viewWirelessUpdate(long vehicleId, Model m) {
		m.addAttribute("vehicleId", vehicleId);
		return "/command/wirelessUpdate";
	}
	

	@ResponseBody
	@RequestMapping("/send.action")
	public JsonMessage execute(long vehicleId,int controlType, String url, String apn,
			String apnUser, String apnPass, String address, @RequestParam(defaultValue="0")  int tcpPort,
			@RequestParam(defaultValue="0")  int udpPort, String vendorId, String hardVersion,
			String softVersion, @RequestParam(defaultValue="0")  int timeout) {

		try {
			TerminalCommand tc = new TerminalCommand();
			tc.setCmdType(JT808Constants.CMD_CONTROL_TERMINAL);
			tc.setCmd("" + controlType); // 控制命令字
			String strTcpPint = this.changeCharset("" + tcpPort, "GBK");
			if (controlType == 1) {
				StringBuilder sb = new StringBuilder();
				sb.append(url).append(";").append(apn).append(";")
						.append(apnUser).append(";").append(apnPass)
						.append(";").append(address).append(";")
						.append(strTcpPint).append(";").append(udpPort)
						.append(";").append(vendorId).append(";")
						.append(hardVersion).append(";").append(softVersion)
						.append(";").append(timeout).append(";");
				tc.setCmdData(sb.toString());
			}
			tc.setVehicleId(vehicleId);
			SendCommand(tc);

			return json(true, tc.getEntityId());
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return json(false, ex.getMessage());
		}
	}

	/**
	 * 字符串编码转换的实现方法
	 * 
	 * @param str
	 *            待转换编码的字符串
	 * @param newCharset
	 *            目标编码
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public String changeCharset(String str, String newCharset) throws Exception {
		if (str != null) {
			// 用默认字符编码解码字符串。
			byte[] bs = str.getBytes();
			// 用新的字符编码生成字符串
			return new String(bs, newCharset);
		}
		return null;
	}


}
